package com.aididi.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aididi.config.OSSProperties;
import com.aididi.util.R;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ：xuzexiang
 * @description：form/data上传
 * @date ： 2021/11/12 9:59
 */

@RequestMapping("/aliyun/oss")
@RestController
@Slf4j
public class OssUploadController {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private OSS ossClient;

    @RequestMapping("/policy")
    public R getPolicy() {
        JSONObject resultBean = new JSONObject();
        // 存储目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dir = sdf.format(new Date())+"/";
        // 签名有效期
        long expireTime = 30;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        // 文件大小
        long maxSize = 100 * 1024 * 1024;
        // 回调
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        String callbackUrl = "http://88.88.88.88.:8888";
        JSONObject callback = new JSONObject();
        callback.put("callbackurl",callbackUrl);

        callback.put("callbackBody","filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        callback.put("callbackBodyType","application/x-www-form-urlencoded");
        // 提交节点
        String action = "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint();
        try {
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String policy = BinaryUtil.toBase64String(binaryData);
            String signature = ossClient.calculatePostSignature(postPolicy);
            String callbackData = BinaryUtil.toBase64String(callback.toString().getBytes("utf-8"));
            resultBean.put("accessid",ossProperties.getAccessKeyId());
            resultBean.put("policy",policy);
            resultBean.put("signature",signature);
            resultBean.put("dir",dir);
            resultBean.put("expire",String.valueOf(expireEndTime / 1000));
            resultBean.put("callback",callbackData);
            resultBean.put("host",action);
            // 返回结果
        } catch (Exception e) {
            log.error("签名生成失败", e);
            return R.error(e.getMessage());
        }
        return R.success(resultBean);
    }
}
